<?php
include_once "baseChannel.php";

class sendCode extends baseChannel
{
    public $code1Url;
    public $code2Url;
    public $loginUrl;
    public $submitUrl;

    public $appid;
    public $apikey;


    public function __construct($setting)
    {
        parent::__construct($setting);
        $this->appid = $setting['appid'] ?? '';
        $this->apikey = $setting['apikey'] ?? "";

        $this->code1Url = $setting['code1Url'] ?? "";
        $this->code2Url = $setting['code2Url'] ?? '';
        $this->loginUrl = $setting['loginUrl'] ?? '';
        $this->submitUrl = $setting['submitUrl'] ?? '';
    }
    /*通用签名方法*/
    // 微网为空也参与签名
    public function getSign($params)
    {
        unset($params['sign']);
        // foreach ($params as $k => $v) {
        //     if (empty($v)) {
        //         unset($params[$k]);
        //     }
        // }
        ksort($params);
        $params['key'] = $this->apikey;
        $str = http_build_query($params);
        // $str = urldecode($str);
        //        echo "签名字符串：".$str.PHP_EOL;
        $sign = md5($str);
        return strtoupper($sign);
    }
    public function sendCode1($mobile, $code)
    {
        // 模拟发码
        $url = $this->code1Url;
        $post_data = [
            'mobile' => $mobile,
            "appid" => $this->appid,
            "code" => $code,
            "timestamp" => time(),
        ];
        // $file_name = $_SERVER['DOCUMENT_ROOT'] . "/../api_resource/logs/" . date('Ymd') . "_pay.log";
        // file_put_contents($file_name, json_encode($post_data) . "\r\n", FILE_APPEND);
        $post_data['sign'] = $this->getSign($post_data);

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['error'] == 0) {
            $data = [
                'error' => 0,
                'msg' => $return_data['msg'] ?? '发送成功',
                "code" => 200,
                "data" => []
            ];
        } else {
            $data =  [
                'error' => 1,
                'msg' => $return_data['msg'] ?? '发送失败',
                'code' => 500
            ];
        }
        return $data;
    }
    public function sendCode2($mobile, $code)
    {
        // 模拟发码
        $url = $this->code2Url;
        $post_data = [
            'mobile' => $mobile,
        ];
        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 200) {
            $data = [
                'error' => 0,
                'msg' => $return_data['msg'] ?? '发送成功',
                "code" => 200
            ];
        } else {
            $data =  [
                'error' => 1,
                'msg' => $return_data['msg'] ?? '发送失败',
                'code' => 500
            ];
        }
        return $data;
    }
    public function validateCode($mobile, $code)
    {
        // 模拟发码
        $url = $this->loginUrl;
        $post_data = [
            'mobile' => $mobile,
            "code" => $code
        ];
        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 200) {
            $data = [
                'error' => 0,
                'msg' => $return_data['msg'] ?? '成功',
                "code" => 200
            ];
        } else {
            $data =  [
                'error' => 1,
                'msg' => $return_data['msg'] ?? '失败',
                'code' => 500
            ];
        }
        return $data;
    }
    /*查询余额*/
    public function queryBalance($params = [])
    {
        $url = $this->api_url;

        $post_data = [
            'appid' => $this->appid,
            // 'uid' => $this->uid,
            'timestamp' => time(),
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['error'] == 0) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['balance'] ?? 0, //余额
                'credit' =>  0, //授信
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['msg'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function queryProduct($params = [])
    {
        $url = $this->api_url;
        $post_data = [
            'act' => 'queryProduct',
            // 'uid' => $this->uid,
            'timestamp' => $this->timestamp,
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $product_map = [];
        if ($return_data['code'] == 200) {
            $product_list = $return_data['data'];
            foreach ($product_list as $product) {
                $items = $product['specs'];
                foreach ($items as $item) {
                    $channel_api_code = $item['spec_code'];
                    $channel_product_status = $item['status'];
                    $channel_product_price = $item['user_price'];

                    $product_map[$channel_api_code] = [
                        'channel_id' => $this->channel_id ?? 0,
                        'channel_api_code' => $channel_api_code,
                        'channel_product_status' => $channel_product_status,
                        'channel_product_price' => $channel_product_price,
                    ];
                }
            }

            return [
                'error' => 0,
                'msg' => '查询成功',
                'data' => $product_map ?? [], //余额
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['msg'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function queryOrder($params)
    {
        $url = $this->api_url;
        $post_data = [
            'appid' => $this->appid,
            // 'uid' => $this->uid,
            'timestamp' => $this->timestamp,
            'order_sn' => $params['channel_order_sn'],
            // 'user_order_sn' => $params['push_order_sn'],
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        if ($sign != $params['sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'voucher' => $return_data['voucher'] ?? '', //凭证
            'post_data' => json_encode($post_data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        // 成功
        if ($return_data['error'] == 0 && $return_data['order_status'] == 3) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '充值完成:' . $return_data['msg'];
        }
        // 失败
        if ($return_data['error'] == 0 && $return_data['order_status'] == 4) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:' . $return_data['msg'];
        }
        // 失败
        if ($return_data['error'] == 0 && $return_data['order_status'] == 5) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:' . $return_data['msg'];
        }
        // // 不存在订单
        // if ($return_data['error'] == 1007) {
        //     $ret['error'] = 1;
        //     $ret['code'] = 404;
        //     $ret['order_status'] = -1;
        //     $ret['msg'] = '订单不存在:' . $return_data['msg'];
        // }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $url = $this->submitUrl;
        $post_data = [
            'mobile' => $mobile,
            'smscode' => $params['captcha'],
            "appid" => $this->appid,
            "timestamp" => time(),
            "code" => $code,
            "callback_url" => $this->callback_url,
            "out_order_sn" => $params['push_order_sn'],
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' =>  $return_data['order_sn'] ?? '',
            'post_data' => json_encode($post_data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => null,
            'channel_balance' => null,
        ];
        if ($return_data['error'] == 0) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            //下单失败 1006 余额不足
            if (isset($return_data['error'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }

        return $ret;
    }

    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = trim($params['order_sn']);
        $this->push_order_sn = $params['out_order_sn'];
        //返回参数
        $res = $this->initCallBackParam();
        //订单状态
        $order_status = $params['order_status'];
        $msg = $params['fail_msg'];
        //凭证
        $pz =  '';
        $res['voucher'] = $pz;

        $sign = $this->getSign($params);

        if ($sign != $params['sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }

        if ($order_status == 3) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
        }

        if ($order_status == 4) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        return $res;
    }
}
